import authRoutes from '@/router/authRoutes'
import basicRoutes from '@/router/basicRoutes'
import { getAuthAPI } from "@/http/api/user";

// 根据用户返回的权限过滤路由
const formatMenuList = (authList) => {
    console.log(4);
    function r(authRoutes) {
        return authRoutes.filter(route => {
            if (authList.includes(route.name)) {
                if (route.children) {
                    route.children = r(route.children)
                }
                return true
            }
        })
    }
    return r(authRoutes)

    // 调试，直接返回所有路由
    // return authRoutes
}


// 权限相关vuex
const auth = {
    namespaced: true,
    state: {
        menuList: [], // 用于存储根据用户权限筛选出来的路由数据
        authList: [], // 用于存储用户的权限
        hasAuthRoutes: false
    },
    getters: {
        userRoutes() {
            return basicRoutes
        }
    },
    mutations: {
        SET_MENULIST(state, menu) {
            state.menuList = menu;
            state.hasAuthRoutes = true;
        },
        SET_AUTHLIST(state, auth) {
            console.log(2);
            state.authList = auth;
        }
    },
    actions: {
        // 请求后端获取用户权限
        async getAuthRoute({commit}) {
            // 请求后端获取角色对应权限，返回结构:['DASHBOARD', 'JOBSQUARE', 'MEETING', 'RESUMEGUIDANCE', 'RESUMETEMPLATE', 'RESUMEEXPLAIN', 'NOTIFY',....]
            await getAuthAPI().then(res => {
                if (res.status) {
                    const authList = res.result.auth ? JSON.parse(res.result.auth) : [];
                    console.log(1);
                    commit('SET_AUTHLIST', authList);
                }
            })
           //  这里目前为了开发方便，不请求接口，因此将数组为空的判断成所有权限都可以
        //    const authList = []
        //    commit('SET_AUTHLIST', authList);

        },
        // 遍历authRoutes获取用户权限对应的路由
        async getMenuList({
            commit,
            state
        }) {
            // 根据authList匹配用户权限
            console.log(3);
            const menuList = formatMenuList(state.authList);
            console.log(5);
            commit('SET_MENULIST', menuList);
            return menuList;
        },
    }
}

export default auth;